package com.cqut.forum.action;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.cqut.forum.entity.PictureGroup;
import com.cqut.forum.entity.User;
import com.cqut.forum.service.PictureGroupService;
import com.cqut.forum.service.PictureService;
import com.cqut.forum.util.FileHandle;
import com.cqut.forum.util.PackTo;

/**
 * 上传action
 * @author yangxun
 */
@Controller
public class UploadAction {
	
	@Resource
	private PictureService pictureService;
	@Resource
	private PictureGroupService pgService;
	@RequestMapping("/picture/upload_picture")
	public String upload(HttpServletRequest req,String index,
			String groupName) throws IllegalStateException, IOException{
		User user = (User) req.getSession().getAttribute("user");
		List<String> url = new ArrayList<String>();
		
		if(user == null){
			return null;
		}
		PictureGroup pg = pgService.getGroupByName(user.getUserId(),groupName);
		MultipartHttpServletRequest request = (MultipartHttpServletRequest)req;
		List<MultipartFile> file = request.getFiles("file"); 
		String[] ind = index.split(",");
		if(!index.equals("")){
			for(int i =0;i<ind.length;i++){
				file.remove(file.get(Integer.parseInt(ind[i])));
			}
		}
		//注：此处本该i<file.size(),但是前台的设计会让file的最后一个元素为空文件，所以此处必须减一
		for(int i =0;i<file.size()-1;i++){
			MultipartFile patch = file.get(i);
			//文件后缀
			String suffix = patch.getOriginalFilename().substring(patch.getOriginalFilename().lastIndexOf("."));  
			//文件名
			//String fileName = user.getUserName()+suffix;  
			String fileName = patch.getOriginalFilename();
			//判定上传的文件格式是否正确
			if ((".jpg.gif.bmp.jpeg.png".indexOf(suffix.toLowerCase()) != -1)) { 
				Integer fileSize = (int) patch.getSize() / 1024; 
				/** 
	             * 如果文件小于10M，则上传文件，否则提示用户不能超过10M 
	             */  
	            if (fileSize <= 10240) { 
	                File f = new File(request.getSession()  
	                        .getServletContext().getRealPath(""));  
	                File picture = new File(f.getParentFile().getPath()+"/user/userPicture/"+user.getUserName()+"/"+groupName);
	                System.out.println(picture.getAbsolutePath()); 
	                /** 
	                 * 判读存储文件路是否存在，不存在则创建 
	                 */  
	                if (! picture.exists()) {  
	                	picture.mkdirs();  
	                    System.out.println("上传文件路径不存在，创建成功！");  
	                }  
	                /** 
	                 * 文件开始上传到服务器上 
	                 */  
	                File img = new File(picture.getAbsolutePath()+"\\"+fileName);
	                patch.transferTo(img);
	                //PictureHandle.createThumbnail(img.getPath(), 150, 150, 1, "e://temp//1.jpg");
	                FileHandle.createThumbnail(img.getPath(),0.2);
	                //将图片的地址保存到数据库
	                url.add("../../../user/userPicture/"+user.getUserName()+"/"+groupName+"/"+fileName);
	                //result = "/pages/user/user_control_photo";
	                if(i==0){
	                	if(pg.getMarkPictureUrl()==null||pg.getMarkPictureUrl().equals("")){
	            			//pg.setMarkPictureUrl(url.get(0));
	            			pg.setMarkPictureUrl(url.get(0));
	            		}
	                }
	            }
	            else{
	            	//result = "请选择小于10M的图片！";
	            }
			}
			else{
				//result = "请选择.jpg.gif.bmp.jpeg.png格式的图片！";
			}
		}
		 
		boolean result = pictureService.insert(PackTo.packToPicture(url, user.getUserId(),pg));
		//设置相册封面图片
		/*if(pg.getMarkPictureUrl()==null||pg.getMarkPictureUrl().equals("")){
			pg.setMarkPictureUrl(url.get(0));
		}*/
		//修改相册数量
		pg.setPictureNumber(pg.getPictureNumber()+url.size());
		pgService.update(pg);
		System.out.println(result);
		return "/pages/picture/upload_back.html";
	}
}
